package com.example.loginProject.service.Impl;

import com.example.loginProject.bean.BaseUser;
import com.example.loginProject.exception.ServiceException;
import com.example.loginProject.mapper.BaseUserMapper;
import com.example.loginProject.service.IBaseUserService;
import com.example.loginProject.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;


/*
service层实现类
 */
@Service
public class BaseUserServiceImpl implements IBaseUserService {
    @Autowired
    private BaseUserMapper mapper;

    private static final int MAX_LOGIN_USERS = 10;
    private static final String LOGIN_USERS_KEY = "login_users";

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public String login(String username, String password) throws ServiceException {
        //使用username信息查找对应的数据库中的用户信息
        BaseUser user = mapper.selectBaseUserByUsername(username);
        if(user == null){
            throw new ServiceException("用户名不存在");
        }

        if(!user.getPassword().equals(password)){
            //密码错误
            throw new ServiceException("密码错误");
        }

        //创建map对象，用来生成token字符串的复合信息
        HashMap<String, Object> userInfo = new HashMap<>();
        userInfo.put("role",user.getRole());
        userInfo.put("Id",user.getUserId());
        userInfo.put("realName",user.getRealname());

        String token = TokenUtil.sign(user.getUserId()+"",userInfo);
        System.out.println(token);
        //TODO: 运用zset存储10个登录账号并更新

        // 操作zset
//        BoundZSetOperations zSetOperations = redisTemplate.boundZSetOps(LOGIN_USERS_KEY);
        BoundListOperations<String,String> ops = redisTemplate.boundListOps(LOGIN_USERS_KEY);
        Long size = ops.size();

        if (size < MAX_LOGIN_USERS) {
            ops.rightPush(username);
        } else {
            ops.trim(0, MAX_LOGIN_USERS - 1);
            ops.rightPush(username);
        }

        redisTemplate.opsForValue().set(user.getUserId()+"",token,12,TimeUnit.HOURS);
//        redisTemplate.expire(token,12, TimeUnit.HOURS);
        return token;

    }

    @Override
    public void loginout() throws ServiceException {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = sra.getRequest();
        String token = request.getHeader("Authorization");

        String userId = TokenUtil.getUserId(token);
        System.out.println("------------"+userId);
        redisTemplate.delete(userId);

    }

    @Override
    public BaseUser currentUserInfo(String token) throws ServiceException {
        String username = TokenUtil.getUserId(token);
        //2.调用mapper查询根据username获取用户的所有信息
        return mapper.selectBaseUserByUsername(username);
    }
}
